<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Scan extends CI_Controller {

	function __construct(){
		parent::__construct();			
		$this->load->model('scan_model');
		$this->load->helper('flexigrid');
		$this->load->helper('file');
		$this->load->helper('download');
		$this->load->library('flexigrid');	
		$this->load->library('form_validation');		
	}

	function index($file_id)
	{
			//ver lib
		
			/*
			 * 0 - display name
			 * 1 - width
			 * 2 - sortable
			 * 3 - align
			 * 4 - searchable (2 -> yes and default, 1 -> yes, 0 -> no.)
			 */
			$colModel['NO'] = array('NO',40,FALSE,'center',0);
			// $colModel['UBAH'] = array('EDIT',50,FALSE,'center',0);
			$colModel['FILE_NAMA'] = array('NAMA FILE',300,TRUE,'center',2);
			$colModel['FILE_URL'] = array('DOWNLOAD',100,FALSE,'center',0);
					
			
			/*
			 * Aditional Parameters
			 */
			$gridParams = array(
			'width' => 'auto',
			'height' => '335',
			'rp' => 15,
			'rpOptions' => '[10,15,20,25,40]',
			'pagestat' => 'Displaying: {from} to {to} of {total} items.',
			'blockOpacity' => 0.5,
			'title' => 'Daftar Keseluruhan Attachment'
			);
			
			/*
			 * 0 - display name
			 * 1 - bclass
			 * 2 - onpress
			 */
			$buttons[] = array('Tambah Data','add','scan_js');
			$buttons[] = array('Hapus Data','delete','scan_js');
			$buttons[] = array('separator');
			$buttons[] = array('Pilih Semua','add','scan_js');
			$buttons[] = array('Batal Memilih Semua','delete','scan_js');
			$buttons[] = array('separator');			
			$buttons[] = array('Kembali ke Arsip','kembali','scan_js');
			$buttons[] = array('separator');
		
		//Build js
		//View helpers/flexigrid_helper.php for more information about the params on this function
		$grid_js = build_grid_js('flex1',site_url("/scan/scan_grid/".$file_id),$colModel,'no','asc',$gridParams,$buttons);
		
		$data['title'] = "Contoh Flexigrid";
		$data['info'] = "Flexigrid";
		$data['js_grid'] = $grid_js;
		$data['version'] = "0.36";
		$data['download_file'] = "Flexigrid_CI_v0.36.rar";
		
		$data['added_js'] = 
			"
			<script type='text/javascript'>
						
			function scan_js(com,grid)
			{
				if (com=='Pilih Semua')
				{
					$('.bDiv tbody tr',grid).addClass('trSelected');
				}
				
				if (com=='Batal Memilih Semua')
				{
					$('.bDiv tbody tr',grid).removeClass('trSelected');
				}

				if (com=='Kembali ke Arsip')
				{
					location.href='".base_url()."index.php/arsip'; 
				}
				
				if (com=='Tambah Data')
				{
					location.href='".base_url()."index.php/scan/input_scan/".$file_id."'; 
				}
				
				if (com=='Hapus Data')
				{
				   if($('.trSelected',grid).length>0){
					   if(confirm('Anda yakin ingin menghapus ' + $('.trSelected',grid).length + ' buah data?')){
							var items = $('.trSelected',grid);
							var itemlist ='';
							for(i=0;i<items.length;i++){
								itemlist+= items[i].id.substr(3)+',';
							}
							$.ajax({
							   type: 'POST',
							   url: '".site_url('/scan/delete_scan')."',
							   data: 'items='+itemlist,
							   success: function(data){
								$('#flex1').flexReload();
								alert(data);
							   }
							});
						}
					} else {
						return false;
					} 
				}          
			}
			</script>
			";
		
		/* $data['notification'] = "";
		if($this->session->userdata('notification')!=''){
			$data['notification'] = "
				<script>
					$(document).ready(function() {
						$.growlUI('Pesan :', '".$this->session->userdata('notification')."'); 
					});
				</script>
			";
		}//end if */	
		
		$data['content'] = $this->load->view('grid',$data,true);
		$this->load->view('main',$data);
		//$this->load->view('grid',$data);
		//$this->load->view('flexigrid',$data);
		
	}
	
	function scan_grid($file_id)
	{
	
		//List of all fields that can be sortable. This is Optional.
		//This prevents that a user sorts by a column that we dont want him to access, or that doesnt exist, preventing errors.
		$valid_fields = array('FILE_NAMA');
		
		$this->flexigrid->validate_post('FILE_ID','asc',$valid_fields);

		$arsip_tahun = substr($file_id,0,4);
		$arsip_id = substr($file_id, 4);

		$records = $this->scan_model->get_scan_grid($arsip_tahun,$arsip_id);
		
		$this->output->set_header($this->config->item('json_header'));
		$no = 1;
		/*
		 * Json build WITH json_encode. If you do not have this function please read
		 * http://flexigrid.eyeviewdesign.com/index.php/flexigrid/example#s3 to know how to use the alternative
		 */
		foreach ($records['records']->result() as $row)
		{

			$record_items[] = array($row->FILE_ID,
			$no,
			/*'<a href=\''.site_url().'/arsip/edit_arsip/'.$row->ARSIP_TAHUN.$row->ARSIP_ID.'/\'><img border=\'0\' src=\''.base_url().'images/main/28.png\'></a> ',*/
			$row->FILE_NAMA,
			'<a href=\''.site_url().'/scan/download_file/'.$row->FILE_ID.'/\'><img border=\'0\' src=\''.base_url().'images/main/dir.png\'></a> '								
			);
			$no++;
		}
		//Print please
		if(isset($record_items))
				$this->output->set_output($this->flexigrid->json_build($records['record_count'],$record_items));
			else
				$this->output->set_output('{"page":"1","total":"0","rows":[]}');
	}

	public function input_scan($file_id)
	{
		if ($this->cek_validasi() == FALSE){
				$data['status'] = 'new';
				$data['file_id'] = $file_id; 
				$data['content'] = $this->load->view('form_scan',$data,TRUE);
				$this->load->view('main',$data);
			}
			else{
				$this->insert_scan($file_id);
			}		
	}

	function cek_validasi() {	
			// Setting Rules
			$this->form_validation->set_rules('file_id', 'File ID', 'required|is_unique');
			
			// Setting Error Message
			$this->form_validation->set_message('required', 'Kolom %s harus diisi!!');
			$this->form_validation->set_message('is_unique', 'Data sudah ada dalam database');
			
			// Setting Delimiter
			$this->form_validation->set_error_delimiters('<li class="error">', '</li>');
			return $this->form_validation->run();
	}

	public function insert_scan($file_id)
	{
		ini_set("memory_limit","50000M");
		ini_set('max_execution_time', 52000);

		// $hasil_rapat_attachment = new HasilRapatAttachment();

		//$key = httpFilterPost("key");
		//$reqId = httpFilterRequest("reqId");

		if( $_FILES['attachment']['name'] != null )
		{
			$url = "./uploads/".$_FILES['attachment']['name'];

			move_uploaded_file($_FILES['attachment']['tmp_name'], $url);

			$records = $this->scan_model->count_all_scan();
			$counter = $records+1;

			$data = array(
				'FILE_ID'	 	=> $file_id.$counter,
				'FILE_NAMA'	 	=> $_FILES['attachment']['name'],
				'FILE_URL'		=> $url,
				'ARSIP_TAHUN'	=> substr($file_id,0,4),
				'ARSIP_ID'		=> substr($file_id,4),
				'STATUS'		=> 1
			);


			/*$hasil_rapat_attachment->setField("NAMA", $_FILES['attachment']['name']);
			$hasil_rapat_attachment->setField("HASIL_RAPAT_ID", $reqId);
			$hasil_rapat_attachment->setField("FILE_NAMA", $_FILES['attachment']['name']);
			$hasil_rapat_attachment->setField("UKURAN", $_FILES['attachment']['size']);
			$hasil_rapat_attachment->setField("FORMAT", $_FILES['attachment']['type']);
			$hasil_rapat_attachment->insert();
			$id = $hasil_rapat_attachment->id;*/
			
			if($_FILES['attachment']['error'] == 0)
			{
				echo "Data Berhasil Tersimpan";
				//echo "1";
			}
			else
			{
				echo "Couldn't upload Blob\n";
			}

			$this->scan_model->add_scan($data);
			redirect('scan/scan/'.$file_id);
		}

		else 

		redirect ('input_scan/'.$file_id);
	}

	function download_file($file_id){
		$download = $this->scan_model->get_scanID($file_id);
		foreach ($download->result() as $row) {
			$data_file = file_get_contents($row->FILE_URL); // Read the file's contents
			$nama_file = $row->FILE_NAMA;			
		}
		force_download($nama_file,$data_file);		
	}

	function delete_scan()
	{
		$scan_ids_post_array = explode(",",$this->input->post('items'));
        $msg = '';
        foreach($scan_ids_post_array as $index => $scan_id){
            if (isset($scan_id) && $scan_id != "") {
                $this->scan_model->delete_scan($scan_id);                      
            
            $msg .= "Attachment dengan id (".$scan_id.") telah berhasil dihapus.\n";
            }
        }
        $this->output->set_header($this->config->item('ajax_header'));
        $this->output->set_output($msg);
	}
}
